package com.dragon.app.concurrent;

import static java.util.concurrent.Executors.newSingleThreadExecutor;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 
 * <p>
 * class: ExecutorTest
 * </p>
 * <p>
 * Description: 线程池测试
 * </p>
 * 
 * @author SmallDragon
 * @date 2019年5月7日
 *
 */
public class ExecutorTest {

	public static void main(String[] args) {

		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
		ExecutorService singleThreadExecutor = newSingleThreadExecutor();
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

		//自定义线程池,推荐使用这种方式创建线程池。
		ExecutorService executorService = new ThreadPoolExecutor(
				2,
				Runtime.getRuntime().availableProcessors() + 1,
				10,
				TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(5),
				new ThreadFactory() {
					private String threadNamePrefix = "ExecutorTest-Thread-";
					private int i = 0;
					@Override
					public Thread newThread(Runnable r) {
						return new Thread(r,threadNamePrefix + ++i);
					}
				},
				new ThreadPoolExecutor.DiscardPolicy());
		

		try {
			for (int i = 0; i < 10; i++) {
				executorService.execute(() -> {
					System.out.println(Thread.currentThread().getName() + ":开始办理业务");
					try {
						TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 1000) + 1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ":===办理业务结束===");
				});
			}
			System.out.println("main调用线程池完成。。。。。");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fixedThreadPool.shutdown();
			singleThreadExecutor.shutdown();
			cachedThreadPool.shutdown();
			scheduledThreadPool.shutdown();
			executorService.shutdown();
		}

		System.out.println("main结束。。。。。");

	}

}
